import Vue from 'vue'
import { sync } from 'vuex-router-sync'
import App from './components/App'
import router from './router'
import store from './store'
import "../build/projectConfig.js";

import VueSimpleMarkdown from 'vue-simple-markdown'
Vue.use(VueSimpleMarkdown)

function redirectLogin () {
    location.href = "/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
     }
    return "";
} 

if (global.requireAuth) {
    const token = getCookie('EL-ADMIN-TOEKN');
    if (token) {
        axios.get(global.SERVER + "/auth/info", {
            headers: {
                "Authorization": "Bearer " + token
            }
        }).then(res => {
            const roles = res.data.roles || [];
            if (roles.indexOf('LAW_USE') < 0) {
                redirectLogin();
            }
        })
            .catch(() => {
                redirectLogin();
            })
    } else {
        redirectLogin();
    }
}

router.beforeEach(function (to, from, next){
    if(Object.keys(to.params).length === 0) {
        Object.assign(to.params, store.state.paramsMap[to.name] || {});
    }
    store.commit('refreshParams', {key: to.name, value: to.params});
    next();
});

sync(store, router)

const app = new Vue({
    router,
    store,
    ...App
})

export { app, router, store }
